import { deptTreeList_get } from '@/api/modules/sys.js'
import { user_assignRole } from '@/api/modules/login.js'
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'

export const useAddRole = indexStore => {
  const roleState = reactive({
    ids: []
  })
  const roleVisible = ref(false)
  const showRoleModal = flag => {
    const { checkIds } = indexStore

    if (flag) {
      if (!checkIds.value.length) {
        ElMessage.error('请选择所分配人员')
        return false
      }
      roleState.ids = []
    }
    roleVisible.value = flag
  }
  const handlerCheckbox = keys => {
    roleState.ids = keys
  }
  const onConfirm = async () => {
    const { checkIds } = indexStore
    if (!roleState.ids.length) {
      ElMessage.error('请选择角色')
      return false
    }
    const { data, code } = await user_assignRole({
      userIds: checkIds.value, // 人员id，必参
      roleIds: roleState.ids // 角色id，必
    })
    if (code === 200) {
      showRoleModal(false)
      ElMessage.success('分配角色成功')
      indexStore.onSearch()
    }
    console.log(data)
  }
  return {
    roleVisible,
    showRoleModal,
    handlerCheckbox,
    onConfirm
  }
}

export const useUserManagerIndex = () => {
  const checkIds = ref([])
  const treeRef = ref()
  const tableRef = ref()
  const treeListData = ref([])
  const expandedKeys = ref([])
  const searchState = reactive({})
  const getDeptTree = async () => {
    const { data } = await deptTreeList_get()
    treeListData.value = data

    expandedKeys.value = data.map(item => item.value)
  }
  const handleNodeClick = e => {
    searchState.deptId = e?.value
    tableRef.value.reset(searchState)
  }
  const handlerCheckbox = keys => {
    checkIds.value = keys
  }
  const onSearch = () => {
    tableRef.value.reset(searchState)
  }
  const onReset = () => {
    resetChecked()
    Object.assign(searchState, {
      name: null,
      mobile: null,
      deptId: null
    })

    tableRef.value.reset(searchState)
  }
  const resetChecked = () => {
    treeRef.value.setCurrentKey(null)
  }
  onMounted(() => {
    getDeptTree()
  })

  return {
    treeRef,
    tableRef,
    treeListData,
    expandedKeys,
    searchState,
    checkIds,
    onReset,
    onSearch,
    handleNodeClick,
    handlerCheckbox
  }
}

export const useUserManager = () => {
  const userManagerIndexStore = useUserManagerIndex()

  const addRoleStore = useAddRole(userManagerIndexStore)

  return {
    addRoleStore,
    userManagerIndexStore
  }
}
